package jacker.bit.price;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;


public class ActivityPrices extends Activity {
	
	ListView pricelist;
	ProgressBar circle;

	PriceHelper mh ;
	PriceHelper mh2 ;
	Cursor cursor = null;
	SimpleCursorAdapter adp0;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.currprices);
        
        //AdCtrl.showAd(this);
        pricelist = (ListView)findViewById(R.id.emails);
        circle  = (ProgressBar)findViewById(R.id.circleProgressBar);
        
        mh = new PriceHelper(this);
        mh2 = new PriceHelper(this);
        
        adp0 = new SimpleCursorAdapter(this,R.layout.currprice
        		,cursor,new String[]{},new int[]{}){
        	@Override
        	public void bindView(View itemView,Context context, Cursor cur){
			
        		super.bindView(itemView, context, cur);
        		
        		TextView titlev = (TextView)itemView.findViewById(R.id.price_title);
        		TextView currentv = (TextView)itemView.findViewById(R.id.current_price);
				TextView highv = (TextView)itemView.findViewById(R.id.high_price);
				TextView alerthv = (TextView)itemView.findViewById(R.id.alert_high_price);
				TextView updatedv = (TextView)itemView.findViewById(R.id.current_date);
				TextView lowv = (TextView)itemView.findViewById(R.id.low_price);
				TextView alertlv = (TextView)itemView.findViewById(R.id.alert_low_price);
				
				
					CurrentPrice price = getPrice(cur);
					
					if(price == null)
						return;
					
						
					titlev.setText(price.getThreadname());
					currentv.setTextColor(price.getUpdown()<0.0f?Color.RED:Color.GREEN);
					currentv.setText(price.getCurrency()+UtilString.price(price.getPrice()));
					updatedv.setText(UtilString.getDateStr(price.getDate()));
					highv.setText(price.getCurrency()+UtilString.price(price.getMaxprice()));
					lowv.setText(price.getCurrency()+UtilString.price(price.getMinprice()));
					alerthv.setText(price.getCurrency()+UtilString.price(price.getOrigprice()
									*(1.0f+0.01f*PrefStore.getUppercent(ActivityPrices.this))));
					alertlv.setText(price.getCurrency()+
							UtilString.price(price.getOrigprice()
							/(1.0f+0.01f*PrefStore.getDownpercent(ActivityPrices.this))
							));
					
				
			}
        };
               
        pricelist.setAdapter(adp0);
        
        pricelist.setOnItemClickListener(new OnItemClickListener(){

			public void onItemClick(AdapterView<?> arg0, View view, int index,
					long arg3) {
				
				Context ctx = getApplicationContext();
				
				cursor.moveToPosition(index);
				CurrentPrice sitem = getPrice(cursor);
				Intent intent = new Intent(ctx,ActivityPrices2.class);
				intent.putExtra(Consts.EXTRA_THREADID, sitem.getThreadid());
				startActivity(intent);
				
			}
        	
        });
        
        
        PriceHelper.registerObserver(processhandler);
        
        refreshView();
        
        Intent intnt = new Intent(this,ServiceTime.class);
    	startService(intnt);
        
        if(mh2.getCurrentPrices().size()==0){
        	Intent intent = new Intent(this,ActivityPlatforms.class);
			startActivity(intent);
        }
    }
    
    
    @Override  
    public boolean onContextItemSelected(MenuItem item) {  
    	AdapterContextMenuInfo menuinfo = (AdapterContextMenuInfo)item.getMenuInfo();
    	cursor.moveToPosition(menuinfo.position);
		CurrentPrice mail = getPrice(cursor);
    	
    	
    	if(item.getItemId() == 10){
    		//mh2.deletePrice(mail.getSid());
    		//refreshView();
    		return true;
    	}
    	
    	
    	return true;
    }
    
    private void loadNews(){
    	if(!UtilAndroid.hasInternet(ActivityPrices.this,true))
    		return;
    	
    	circle.setVisibility(View.VISIBLE);
    	loadtime = System.currentTimeMillis();
    	
    	startService(new Intent(this,ServiceCheckPrice.class));
        
        /*new Thread(new Runnable(){

			@Override
			public void run() {
				PriceChecker.checkPrices(getApplicationContext());
				
			}
        	
        }).start();*/
    }
    
    long loadtime = System.currentTimeMillis(); // first time not load, update server must load
    long viewtime = 888L;
    @Override
	public void onResume() {
		super.onResume();
		
		NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	nm.cancelAll();
    	
			if(loadtime < PrefStore.configTime){
					loadNews();
				
			}
	}
    
    private void refreshView(){
    	//circle.setVisibility(View.VISIBLE);
		android.os.Message msg = new android.os.Message();
		msg.what = Consts.MSG_DATA_UPDATE;
		msg.obj = System.currentTimeMillis();
		processhandler.sendMessage(msg);
    }
    
    private void hideProgress(){
    	//circle.setVisibility(View.VISIBLE);
		android.os.Message msg = new android.os.Message();
		msg.what = Consts.MSG_UI_PROGRESS_OFF;
		processhandler.sendMessageDelayed(msg, 200);
    }
    
    
    Handler processhandler = new Handler(){
		@Override
    	public void handleMessage(android.os.Message msg) {
			if(msg.what == Consts.MSG_DATA_UPDATE 
					|| msg.what == Consts.MSG_MAIN_DATA_UPDATE){
				UtilLog.d("request time: "+msg.obj+" viewtime: "+viewtime);
				   if(msg.obj!=null && (Long)msg.obj>viewtime){
					   getPrices();
					   /*synchronized(chkctx){
						   chkctx.notifyAll();
					   }*/
				   }
				return;
			}
			
			if(msg.what == Consts.MSG_UI_PROGRESS_OFF){
				circle.setVisibility(View.GONE);
				return;
			}
			
			
		}
	};
	
    
    @Override
    public void onBackPressed(){
    	if(cursor!=null && !cursor.isClosed())
    		cursor.close();
    	
    	mh.getWritableDatabase().close();
    	
    	PriceHelper.removeObserver(processhandler);
    	
    	NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    	nm.cancelAll();
    	
    	//MailReceiver.tempid = 0;
    	
    	super.onBackPressed();
    }
    
     
    public void getPrices(){
    	UtilLog.d( "Load price data...");
    	
    	
    	cursor = mh.getWritableDatabase().query("CURRPRICE"
				, new String[]{"sid _id","threadid","price","origprice","currency","threadname","maxprice","minprice","pricedate"}
				, null, null
				, null, null
				, null);
    	//post run for delayed msg
    	viewtime = System.currentTimeMillis();
    	
		adp0.changeCursor(cursor);
		adp0.notifyDataSetChanged();
		
		//UtilLog.d( "Load mails data... finish, adp items enabled: "+emaillist.isShown());
	}
    
    private CurrentPrice getPrice(Cursor cur){
    	CurrentPrice cp = new CurrentPrice();
    	cp.setThreadid(cursor.getString(cursor.getColumnIndex("threadid")));
    	cp.setThreadname(cursor.getString(cursor.getColumnIndex("threadname")));
		cp.setPrice(cursor.getFloat(cursor.getColumnIndex("price")));
		cp.setOrigprice(cursor.getFloat(cursor.getColumnIndex("origprice")));
		cp.setCurrency(cursor.getString(cursor.getColumnIndex("currency")));
		cp.setMaxprice(cursor.getFloat(cursor.getColumnIndex("maxprice")));
		cp.setMinprice(cursor.getFloat(cursor.getColumnIndex("minprice")));
		cp.setDate(cursor.getLong(cursor.getColumnIndex("pricedate")));
    	return cp;
    }
    

	@Override
    public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE,5,5,R.string.check_price_action)
			.setIcon(R.drawable.ic_menu_refresh);
		//menu.add(Menu.NONE,Consts.MENU_DELETE,60,R.string.clear_action)
			//.setIcon(android.R.drawable.ic_menu_delete);
		menu.add(Menu.NONE,50,50,R.string.prefs_title)
			.setIcon(android.R.drawable.ic_menu_preferences);
		menu.add(Menu.NONE,30,30,R.string.platforms_choose)
		.setIcon(android.R.drawable.ic_menu_agenda);
		menu.add(Menu.NONE,60,60,R.string.help_action)
		.setIcon(android.R.drawable.ic_menu_help);
		//menu.add(Menu.NONE,65,65,"To developer");
		//menu.add(Menu.NONE,70,70,"Help");
		return true;
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
		if(item.getItemId()==5){
			//cache.clear();
			loadNews();
			return true;
		}else if(item.getItemId()==50){
			Intent intent = new Intent(this,ActivitySettings.class);
			startActivity(intent);
			return true;
		}else if(item.getItemId()==30){
			Intent intent = new Intent(this,ActivityPlatforms.class);
			startActivity(intent);
			return true;
		}else if(item.getItemId()==60){
			Uri uri = Uri.parse(getString(R.string.help_link));
			Intent intent = new Intent(Intent.ACTION_VIEW,uri);
			startActivity(intent);
			return true;
		}
		return false;
	}
    

    
}